<?php

namespace App\Http\Controllers;

use App\Model\Tag;
use Illuminate\Http\Request;

class TagController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $tags = Tag::paginate(5);
        return view('tag.index',compact('tags'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('tag.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, Tag $tag)
    {
        //
        $this->validate($request,[
            'name'=>'required|min:1|max:12|unique:tags',
        ]);

        $tag->name = $request->name;
        $res = $tag->save();
        if ($res){
            return [
                'error' => 0,
                'info' => '添加成功',
            ];
        }
        return [
            'error'=>1,
            'info' => '添加失败,自己想想原因',
        ];
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Tag $tag)
    {
        //
        return view('tag.edit',compact('tag'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Tag $tag)
    {
        //
        $this->validate($request,[
            'name'=>'required|min:1|max:12|unique:users,'.$tag->id,
        ]);

        $tag->name = $request->name;
        $res = $tag->save();
        if ($res){
            return [
                'error' => 0,
                'info' => '修改成功',
            ];
        }
        return [
            'error'=>1,
            'info' => '修改失败,自己想想原因',
        ];

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Tag $tag)
    {
        //
        $tag->articles()->detach();
        $tag->delete();
    }
}
